# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   File Name：     ModulePermission
   Description :
   Author :       tomtoto
   date：          2018/8/23
-------------------------------------------------
   Change Activity:
                   2018/8/23:
-------------------------------------------------
"""
# -*- coding: utf-8 -*-
from rest_framework.permissions import BasePermission, SAFE_METHODS

class ModulePermission(BasePermission):

    authenticated_users_only = True

    def has_perms(self, user, perms):
        user_perms = user.get_all_permissions()
        for perm in perms:
            if perm in user_perms:
                return True
        return False

    def get_module_perms(self, view):
        return [view.app_name+'.{}'.format(perm) for perm in view.module_perms]

    def has_permission(self, request, view):

        if request.user.is_superuser:
            return True

        assert view.module_perms or not isinstance(view.module_perms, list), ()

        if getattr(view, '_ignore_model_permissions', False):
            return True

        if hasattr(view, 'get_queryset'):
            queryset = view.get_queryset()
        else:
            queryset = getattr(view, 'queryset', None)

        assert queryset is not None, ()

        return (
            request.user and
            (request.user.is_authenticated or not self.authenticated_users_only) and
            self.has_perms(request.user, self.get_module_perms(view))
        )


class ModulePermissionOrReadOnly(ModulePermission):
    """
    The request is authenticated with ModulePermission, or is a read-only request.
    """

    def has_permission(self, request, view):
        return (request.method in SAFE_METHODS or super(ModulePermissionOrReadOnly, self).has_permission(request, view))